import React, { useEffect, useState } from "react";
import { Button, message } from "antd";
import { LeftCircleOutlined, RightCircleOutlined } from "@ant-design/icons";
import { useStore } from "@/store";
import { setStore } from "@/services/system.service";
import { useLocation, useNavigate } from "react-router-dom";

import TextModal from "./TextModal";
import ImageModal from "./ImageModal";
import VideoModal from "./VideoModal";
import CodeModal from "./CodeModal";
import BackModal from "./BackModal";

const SlideTop = () => {
  const navigate = useNavigate();
  const { search, pathname } = useLocation();
  // 创建一个URLSearchParams对象
  const params = new URLSearchParams(search);
  // 获取title和id的值
  const query = {
    title: params?.get("title") || "",
    id: params?.get("id") || "",
  };

  // setCurrentPresentation(id);
  const {
    sildeFatherId,
    slideFatnerList,
    slideList,
    currentSlideIndex,
    setCurrentPresentation,
    slideTitle,
    slideImage,
    sildeBgType,
    sildeBgVal,
    sildeBgVal2,
  } = useStore();
  const [visibleTextModal, setVisibleTextModal] = useState(false);
  const [visibleImageModal, setVisibleImageModal] = useState(false);
  const [visibleBackModal, setVisibleBackModal] = useState(false);
  const [visibleVideoModal, setVisibleVideoModal] = useState(false);
  const [visibleCodeModal, setVisibleCodeModal] = useState(false);
  const [isAdd, setIsAdd] = useState(true);
  const [elementsIndex, setElementsIndex] = useState(0);

  useEffect(() => {
    // 定义键盘事件处理函数
    const handleKeyDown = (event) => {
      switch (event.key) {
        case "ArrowLeft":
          handleLeftArrow();
          break;
        case "ArrowRight":
          handleRightArrow();
          break;
        default:
          break;
      }
    };

    // 添加键盘事件监听器
    window.addEventListener("keydown", handleKeyDown);
    // 返回一个清理函数，在组件卸载时移除事件监听器
    return () => {
      window.removeEventListener("keydown", handleKeyDown);
    };
  }, [currentSlideIndex]); // 空数组作为依赖项，确保只在组件挂载和卸载时运行一次

  const handleLeftArrow = () => {
    if (currentSlideIndex === 1) return;
    setCurrentPresentation(currentSlideIndex - 1);
    console.log("Left arrow key pressed");
    // 在这里执行左箭头对应的事件
  };

  const handleRightArrow = () => {
    if (currentSlideIndex === slideList.length) return;
    setCurrentPresentation(currentSlideIndex + 1);
    console.log("Right arrow key pressed");
    // 在这里执行右箭头对应的事件
  };

  // 双击进入编辑状态
  const handlePassEvent = (e) => {
    if (e && e.detail) {
      if (e.detail.type === "Text") {
        setVisibleTextModal(true);
        setTimeout(() => {
          setVisibleTextModal(false);
        });
        setIsAdd(false);
        setElementsIndex(e.detail.elementsIndex);
      }
      if (e.detail.type === "Image") {
        setVisibleImageModal(true);
        setTimeout(() => {
          setVisibleImageModal(false);
        });
        setIsAdd(false);
        setElementsIndex(e.detail.elementsIndex);
      }
      if (e.detail.type === "Video") {
        setVisibleVideoModal(true);
        setTimeout(() => {
          setVisibleVideoModal(false);
        });
        setIsAdd(false);
        setElementsIndex(e.detail.elementsIndex);
      }
      if (e.detail.type === "Code") {
        setVisibleCodeModal(true);
        setTimeout(() => {
          setVisibleCodeModal(false);
        });
        setIsAdd(false);
        setElementsIndex(e.detail.elementsIndex);
      }
    }

    // if (e && e.detail) {
    //   setBackStatus(e.detail.isEdit);
    // }
  };

  useEffect(() => {
    document.addEventListener("passEvent", handlePassEvent);
    return () => {
      document.removeEventListener("passEvent", handlePassEvent);
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const handleSave = (data) => {
    const storeBro = {
      slideList,
      slideTitle,
      slideImage,
      id: sildeFatherId,
      sildeBgType,
      sildeBgVal,
      sildeBgVal2,
    };
    // const storeBro = { slideList, slideTitle };
    // 保存的时候分新建和编辑：
    // 新建==就是给slideFatnerList后面加一个
    // 编辑==就是sildeFatherId进行更新的操作，更新slideTitle、slideList、id
    if (query && query.id) {
      const slideFatnerListBro = [...slideFatnerList];
      const flagIndex = slideFatnerListBro.findIndex(
        (item) => item?.id === query?.id
      );
      if (flagIndex !== -1) {
        slideFatnerListBro[flagIndex] = { ...storeBro };
        setStore({ store: slideFatnerListBro }).then((res) => {
          // setStore({ store: [] }).then((res) => {
          message.success("保存成功");
          navigate("/dashboard");
        });
      }
      // 走编辑
      // updateSlideTitle(query.title);
    } else {
      // 走新建
      slideFatnerList.push(storeBro);
      setStore({ store: slideFatnerList }).then((res) => {
        message.success("保存成功");
        navigate("/dashboard");
      });
    }
  };

  const disableOpen = () => {
    if (currentSlideIndex === 0 || slideList.length === 0) {
      message.error("请先新增一张幻灯片");
      return;
    }
  };

  return (
    <div
      style={{
        display: "flex",
        alignContent: "center",
        justifyContent: "space-between",
        width: "100%",
        height: "62px",
        padding: "16px",
        backgroundColor: "white",
        borderBottom: "1px solid #e8e8e8",
      }}
    >
      <div
        style={{ display: "flex", alignContent: "center", color: "#6b7280" }}
      >
        <Button
          type="link"
          disabled={currentSlideIndex === 1}
          onClick={() => {
            setCurrentPresentation(currentSlideIndex - 1);
          }}
        >
          <LeftCircleOutlined style={{ fontSize: 20, cursor: "pointer" }} />
        </Button>
        <span style={{ lineHeight: "28px" }}>
          当前第{currentSlideIndex}页,共{slideList.length}页
        </span>
        <Button
          type="link"
          disabled={currentSlideIndex === slideList.length}
          onClick={() => {
            setCurrentPresentation(currentSlideIndex + 1);
          }}
        >
          <RightCircleOutlined style={{ fontSize: 20, cursor: "pointer" }} />
        </Button>
      </div>
      <div
        style={{
          display: "flex",
          width: 480,
          justifyContent: "space-between",
          marginLeft: 40,
        }}
      >
        <Button
          type="primary"
          onClick={() => {
            if (currentSlideIndex === 0 || slideList.length === 0) {
              message.error("请先新增一张幻灯片");
              return;
            }
            setVisibleTextModal(true);
            setTimeout(() => {
              setVisibleTextModal(false);
            });
            setIsAdd(true);
          }}
        >
          新增文本
        </Button>
        <Button
          type="primary"
          onClick={() => {
            if (currentSlideIndex === 0 || slideList.length === 0) {
              message.error("请先新增一张幻灯片");
              return;
            }
            setVisibleImageModal(true);
            setTimeout(() => {
              setVisibleImageModal(false);
            });
            setIsAdd(true);
          }}
        >
          新增图片
        </Button>
        <Button
          type="primary"
          onClick={() => {
            if (currentSlideIndex === 0 || slideList.length === 0) {
              message.error("请先新增一张幻灯片");
              return;
            }
            setVisibleVideoModal(true);
            setTimeout(() => {
              setVisibleVideoModal(false);
            });
            setIsAdd(true);
          }}
        >
          新增视频
        </Button>
        <Button
          type="primary"
          onClick={() => {
            if (currentSlideIndex === 0 || slideList.length === 0) {
              message.error("请先新增一张幻灯片");
              return;
            }
            setVisibleCodeModal(true);
            setTimeout(() => {
              setVisibleCodeModal(false);
            });
            setIsAdd(true);
          }}
        >
          新增代码
        </Button>
        <Button
          type="primary"
          onClick={() => {
            setVisibleBackModal(true);
            setTimeout(() => {
              setVisibleBackModal(false);
            });
          }}
        >
          设置背景
        </Button>
      </div>
      <div
        style={{
          display: "flex",
          width: 400,
          justifyContent: "right",
          marginLeft: 40,
        }}
      >
        <Button
          style={{ marginRight: 10 }}
          onClick={() => {
            handleSave();
          }}
        >
          保存
        </Button>
        {/* <Button style={{ marginRight: 10 }} onClick={() => {}}>
          返回
        </Button> */}
        <Button
          type="link"
          onClick={() => {
            navigate("/dashboard");
          }}
        >
          返回
        </Button>
      </div>
      {/* 文本弹窗 */}
      <TextModal
        visibleTextModal={visibleTextModal}
        isAdd={isAdd}
        elementsIndex={elementsIndex}
      />
      {/* 图片弹窗 */}
      <ImageModal
        visibleImageModal={visibleImageModal}
        isAdd={isAdd}
        elementsIndex={elementsIndex}
      />
      <BackModal
        visibleBackModal={visibleBackModal}
        isAdd={isAdd}
        elementsIndex={elementsIndex}
      />
      {/* 视频弹窗 */}
      <VideoModal
        visibleVideoModal={visibleVideoModal}
        isAdd={isAdd}
        elementsIndex={elementsIndex}
      />
      {/* 代码弹窗 */}
      <CodeModal
        visibleCodeModal={visibleCodeModal}
        isAdd={isAdd}
        elementsIndex={elementsIndex}
      />
    </div>
  );
};

export default SlideTop;
